package com.bzframework.bookkeeping.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bzframework.bookkeeping.entity.BookkeepingRoomEntity;
import com.bzframework.bookkeeping.entity.BookkeepingRoomPlayerEntity;
import com.bzframework.bookkeeping.enums.BookkeepingAmountUnitEnum;
import com.bzframework.bookkeeping.enums.BookkeepingRoomPlayerStatusEnum;
import com.bzframework.bookkeeping.enums.BookkeepingRoomRoleEnum;
import com.bzframework.bookkeeping.enums.BookkeepingRoomStatusEnum;
import com.bzframework.bookkeeping.manager.RoomCodeGenerator;
import com.bzframework.bookkeeping.mapper.BookkeepingRoomMapper;
import com.bzframework.bookkeeping.service.BookkeepingRoomPlayerService;
import com.bzframework.bookkeeping.service.BookkeepingRoomService;
import com.bzframework.core.response.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author bingzhong
 * @Date 2025/11/2
 */
@Service
@RequiredArgsConstructor
public class BookkeepingRoomServiceImpl extends ServiceImpl<BookkeepingRoomMapper, BookkeepingRoomEntity> implements BookkeepingRoomService {

    private final BookkeepingRoomPlayerService bookkeepingRoomPlayerService;

    private final RoomCodeGenerator roomCodeGenerator;

    @Override
    @Transactional
    public boolean createRoom(String userId) {
        BookkeepingRoomEntity bookkeepingRoomEntity = new BookkeepingRoomEntity();
        bookkeepingRoomEntity.setCreatorId(userId);
        bookkeepingRoomEntity.setRole(BookkeepingRoomRoleEnum.HOMEOWNER.getRole());
        bookkeepingRoomEntity.setCurrentPlayers(1);
        bookkeepingRoomEntity.setRoomCode(roomCodeGenerator.generateRoomCode());
        bookkeepingRoomEntity.setRoomStatus(BookkeepingRoomStatusEnum.PROGRESSING.getStatus());
        bookkeepingRoomEntity.setAmountUnit(BookkeepingAmountUnitEnum.SCORE.getUnit());
        boolean savedRoom = this.save(bookkeepingRoomEntity);
        if (savedRoom) {
            throw new BusinessException("房间创建失败");
        }
        BookkeepingRoomPlayerEntity bookkeepingRoomPlayerEntity = new BookkeepingRoomPlayerEntity();
        bookkeepingRoomPlayerEntity.setRoomId(bookkeepingRoomPlayerEntity.getRoomId());
        bookkeepingRoomPlayerEntity.setUserId(userId);
        bookkeepingRoomPlayerEntity.setPlayerName(userId);
        bookkeepingRoomPlayerEntity.setJoinTime(System.currentTimeMillis());
        bookkeepingRoomPlayerEntity.setStatus(BookkeepingRoomPlayerStatusEnum.IN_ROOM.getStatus());
        bookkeepingRoomPlayerEntity.setAmount(0D);
        boolean savedRoomPlayer = bookkeepingRoomPlayerService.save(bookkeepingRoomPlayerEntity);
        if (savedRoomPlayer) {
            throw new BusinessException("房间创建失败");
        }
        return true;
    }
}
